package com.test.kupi.fw;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;

import com.test.kupi.page.object.PageMain;
import com.test.kupi.page.object.PageSearch;

public class SearchHelper extends HelperBase{

	PageMain pagemain = new PageMain(driver);
	PageSearch pagesearch = new PageSearch(driver);
	
	public SearchHelper(ApplicationManager manager) {
		super(manager);
	}

	public SearchHelper checkCurrency() {
		pagemain.defaultCur();
		return this;
	}
	
	public SearchHelper setCurrency(String text) {
		pagemain.chooseCur(text);
		return this;
	}
	
	public SearchHelper searchItem(String text) {
		pagesearch.searchItem(text).clickSearchBut();
		return this;
	}

	public SearchHelper filterItem(String text) throws InterruptedException {
		pagesearch.sortPrice(text);
		return this;
	}

	public List<String> searchResult() {
		List<String> list = new ArrayList<String>();
		List<WebElement> elements = driver.findElements(By.xpath("//div[@class = 'b-item-list']/descendant::div[@class = 'item_title']/h2/a")); 
		for (WebElement element : elements) {
			String s = element.getText();
			list.add(s);
		}
		
		String search = "Apple iPhone 4 (8Gb)";
		String[] chars = search.split(" ");
		
		for (String string : chars) {
			string = string.toLowerCase(); 
			if(string.contains("(") || string.contains(")")) {
				string = string.replace("(", "").replace(")", "");
			}
			
			for (int size = list.size(); size>0; size--) {
				if (!list.get(size-1).toLowerCase().contains(string)) {
					list.remove(size-1);
				}
				System.out.println("=== "+string);
				System.out.println(list);
			}
		}
		return list;
	}
	
	public String minPrice() {
		List<WebElement> elements = driver.findElements(By.xpath("//div[@class = 'price']"));
		int i = 0;
		String price = "1";
		for (WebElement element : elements) {
			String s = element.getText();
			String[] s1 = s.split(" ");
			try {
				i = Integer.parseInt(s1[0]);
			} catch (Exception e){
				i = Integer.parseInt(s1[1]);				
			}
			System.out.println(s+"  "+i);
		}
		return price;
	}
}
